const express = require('express');
const route = express.Router();
const pool = require('../pool');
route.post("/add", (req, res) => {
  var obj = req.body;
  obj.selected=JSON.parse(obj.selected);
  console.log(obj);
   //检测uid是否为空
   if (!obj.uid) {
    return res.json({ code: 401, msg: "uid required" });
  }
  //检测订单金额是否为空
  if (!obj.orderAmount) {
    return res.json({ code: 402, msg: "orderAmount required" });
  }
  // 检测商品是否为空
  if (!obj.selected) {
    return res.json({ code: 403, msg: "no course selected" });
  }
  // 创建以秒为单位的时间戳
  var created=parseInt(new Date().getTime()/1000);
  // 根据传入的数据创建订单信息
  var order={
    userId:parseInt(obj.uid),
    amount:parseInt(obj.orderAmount),
    created:created
  };
  // 向orders表添加订单
  let sql="insert into orders set ?";
  console.log(0000);
  pool.query(sql,[order],(err,result)=>{
    if(err) throw err;
    console.log(result,111111);
    if(result.affectedRows>0){
      // 添加成功
      var orderId=result.insertId;
      var details=[];
      for(var i=0;i<obj.selected.length;i++){
        var tmp=[];
        tmp.push(orderId);
        tmp.push(obj.selected[i].courseId);
        tmp.push(obj.selected[i].count);
        details.push(tmp);
      }
      let sql="insert into orders_detail (orderId,courseId,count) values ?"
      pool.query(sql,[details],(err,result)=>{
        if(err) throw err;
        if(result.affectedRows>0){
          console.log(result);
          res.json({code:200,msg:"success",data:{orderId:orderId}})
        }
      })
    }else{
      res.json({code:301,msg:"failed"})
    }
  })
})
route.post("/list",(req,res)=>{
  var obj=req.body;
  console.log(obj);
  let sql="SELECT * FROM orders,orders_detail,course WHERE orders.oid=orders_detail.orderId AND orders_detail.courseId=course.cid AND orders.userId=?";
  pool.query(sql,[obj.userId],(err,result)=>{
    console.log(result);
    if(err) throw err;
    console.log(333333);
    if(result.length>0){
      console.log(22222);
      res.json({code:200,msg:"success",data:{result}});
    }
  })
})
module.exports = route;